<!--
 * Copyright ©
 * #  
 * @author: zw
 * @date: 2021-08-08 
 -->


<template>
  <el-form :model="form" :rules="rules" ref="FORM">
    <el-form-item prop="username"><el-input v-model="form.username" prefix-icon="el-icon-user-solid" /></el-form-item>
    <el-form-item prop="password"><el-input v-model="form.password" prefix-icon="el-icon-unlock" type="password" /></el-form-item>

    <el-form-item>
      <el-button type="primary" @click="login">登录</el-button>
      <el-button type="danger" @click="resetform">重置</el-button>
    </el-form-item>

  </el-form>
</template>

<script>
  import { defineComponent, reactive, toRefs, ref } from 'vue'
  import { ElMessage, ElNotification } from 'element-plus';
  import router from '../router'
  function useReset(ref) {
    const resetform = () => {
      ref.value.resetFields();
    };
    return {resetform}
  };

  function useLogin(ref, state) {
    const login = () => {
      ref.value.validate(async valid => {
        if (!valid) return ElMessage.error('验证未通过');
        const params = { username: state.form.username, password: state.form.password }
        //@ts-ignore;
        const { data, code, token } = await ajax({url: 'user/login', method: 'post', params })
        if (code !== 0) return ElMessage.error('登录失败');
        sessionStorage.setItem("token", token);
        router.push("/");
        ElNotification({
           title: '提示', type: 'success', message: '登录成功',
        })
      });
    };
    return { login }
  }
  export default defineComponent({
    name: '~login',
    setup(props, {emit, slots}) {
      const FORM = ref()
      const state = reactive({
        form: { username: "admin", password: "123456" },
        rules: { username: [{ required: true, message: '请输入用户名', trigger: 'blur'}, {min: 3, max: 10, message: 'min is 3, max is 10!', trigger: 'blur'}], password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 10, message: "min is 6, max is 10", trigger: "blur" }] },
      });

     return {
       FORM,
       ...toRefs(state),
       ...useReset(FORM),
       ...useLogin(FORM, state)
      }
     }
  })

</script>

<style lang='css' scoped>
.el-form {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  margin: 0 auto;
  padding: 20px 30px;
}
</style>
